package cn.twh.wall.filter;

import cn.twh.wall.config.WallConfig;
import cn.twh.wall.service.JsonWallService;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebFilter
@Component
public class UrlToApiFilter implements Filter {

    public static final String API = "api";
    @Autowired
    WallConfig wallConfig;

    @Autowired
    private JsonWallService wallService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        Map<String, String> uriToApi = wallConfig.getUriToApi();
        String api = req.getParameter(API);
        if (StringUtils.isBlank(api)) {
            if (uriToApi.containsKey(req.getRequestURI())) {
                api = uriToApi.get(req.getRequestURI());
            } else {
                chain.doFilter(request, response);
                return;
            }
        }
        byte[] body = binaryReader(req);
        // 处理
        JSONObject reqJson = JSONObject.parseObject(new String(body));
        Map<String, String> headers = new HashMap<>();
        Enumeration<String> headerNames = req.getHeaderNames();
        while (!headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            headers.put(key, req.getHeader(key));
        }
        response.getOutputStream()
                .write(wallService.dpHandler(reqJson, headers, api).getBytes(Charsets.UTF_8));
        return;
    }

    byte[] binaryReader(HttpServletRequest request) throws IOException {
        int len = request.getContentLength();
        if (len == -1) {
            return new byte[0];
        }
        ServletInputStream input = request.getInputStream();
        byte[] buffer = new byte[len];
        input.read(buffer, 0, len);
        return buffer;
    }
}